package NetWork.UDPDome003;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * ClassName:ReceiveMessage002
 * Package:NetWork.UDPDome003
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/3/7-21:08
 * @Version:v1.0
 */
public class ReceiveMessage002 {
    public static void main(String[] args) throws IOException {
        //创建 MulticastSocket 对象
        MulticastSocket ms = new MulticastSocket(10086);
        //将当前本机,添加到224.0.0.1的这一组当中
        InetAddress address = InetAddress.getByName("224.0.0.1");
        ms.joinGroup(address);
        //创建DatagramPacket数据包对象
        byte[]bytes=new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);

        //接受数据
        ms.receive(dp);

        //解析数据
        String ip = dp.getAddress().getHostAddress();
        byte[] data = dp.getData();
        int length = dp.getLength();
        String name = dp.getAddress().getHostName();

        System.out.println("ip为："+ip +",主机名为："+name+"的人发送了数据："+new String(data,0,length));

        //释放资源
        ms.close();
    }
}
